package com.teichmann.core.targets;

import java.io.IOException;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.htmlparser.Node;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.Tag;
import org.htmlparser.lexer.Lexer;
import org.htmlparser.tags.LinkTag;
import org.htmlparser.tags.TableColumn;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;
import org.htmlparser.visitors.NodeVisitor;

import com.teichmann.bo.Car;
import com.teichmann.bo.Seller;
import com.teichmann.core.Page;
import com.teichmann.core.annotations.Delimiter;
import com.teichmann.core.annotations.InternalPages;
import com.teichmann.core.annotations.Url;
import com.teichmann.core.util.ConnectionUtils;

@InternalPages( { 
		@Url(value = "http://www.autocarro.com.br/13automoveis/index2.php"),
		@Url(value = "http://www.autocarro.com.br/3rs/index2.php"),
		@Url(value = "http://www.autocarro.com.br/abudcamionetes/index2.php"),
		@Url(value = "http://www.autocarro.com.br/absoluto/index2.php"),
		@Url(value = "http://www.autocarro.com.br/acropole/index2.php"),
		@Url(value = "http://www.autocarro.com.br/alternativa/index2.php"),
		@Url(value = "http://www.autocarro.com.br/almeida/index2.php"),
		@Url(value = "http://www.autocarro.com.br/alvoradaautomoveis/index2.php"),
		@Url(value = "http://www.autocarro.com.br/amarildo/index2.php"),
		@Url(value = "http://www.autocarro.com.br/amg/index2.php"),
		@Url(value = "http://www.autocarro.com.br/aquinoveiculos/index2.php"),
		@Url(value = "http://www.autocarro.com.br/astra/index2.php"),
		@Url(value = "http://www.autocarro.com.br/atibaia/index2.php"),
		@Url(value = "http://www.autocarro.com.br/autodez/index2.php"),
		@Url(value = "http://www.autocarro.com.br/autoclassic/index2.php"),
		@Url(value = "http://www.autocarro.com.br/automania/index2.php"),
		@Url(value = "http://www.autocarro.com.br/autosul/index2.php"),
		@Url(value = "http://www.autocarro.com.br/autonal/index2.php"),
		@Url(value = "http://www.autocarro.com.br/autostilo/index2.php"),
		@Url(value = "http://www.autocarro.com.br/baixinho/index2.php"),
		@Url(value = "http://www.autocarro.com.br/br/index2.php"),
		@Url(value = "http://www.autocarro.com.br/carburgonh/index2.php"),
		@Url(value = "http://www.autocarro.com.br/carlotto/index2.php"),
		@Url(value = "http://www.autocarro.com.br/carrodez/index2.php"),
		@Url(value = "http://www.autocarro.com.br/classic/index2.php"),
		@Url(value = "http://www.autocarro.com.br/civic/index2.php"),
		@Url(value = "http://www.autocarro.com.br/confrariadocarro/index2.php"),
		@Url(value = "http://www.autocarro.com.br/davi/index2.php"),
		@Url(value = "http://www.autocarro.com.br/deltacar/index2.php"),
		@Url(value = "http://www.autocarro.com.br/edmilson/index2.php"),
		@Url(value = "http://www.autocarro.com.br/edson-sinos/index2.php"),
		@Url(value = "http://www.autocarro.com.br/eduardocimirro/index2.php"),
		@Url(value = "http://www.autocarro.com.br/futura/index2.php"),
		@Url(value = "http://www.autocarro.com.br/hamburgo/index2.php"), 
		@Url(value = "http://www.autocarro.com.br/klippcar/index2.php"),
		@Url(value = "http://www.autocarro.com.br/kolling/index2.php"),
		@Url(value = "http://www.autocarro.com.br/maxximotors/index2.php"),
		@Url(value = "http://www.autocarro.com.br/konzenveiculos/index2.php"),
		@Url(value = "http://www.autocarro.com.br/midiaveiculos/index2.php"),
		@Url(value = "http://www.autocarro.com.br/model/index2.php"),
		@Url(value = "http://www.autocarro.com.br/nobrecarr/index2.php"),
		@Url(value = "http://www.autocarro.com.br/n1/index2.php"),
		@Url(value = "http://www.autocarro.com.br/patrianova/index2.php"),
		@Url(value = "http://www.autocarro.com.br/paulousui/index2.php"),
		@Url(value = "http://www.autocarro.com.br/pingo/index2.php"),
		@Url(value = "http://www.autocarro.com.br/prisma-sap/index2.php"),
		@Url(value = "http://www.autocarro.com.br/vilnei/index2.php"),
		@Url(value = "http://www.autocarro.com.br/vitoria/index2.php"),
		@Url(value = "http://www.autocarro.com.br/worldcar/index2.php")
		})
@Delimiter(tag = "tr", attribute = "bgcolor", value = "#f0f0f0")
public class AutoCarro implements Page {

	private int countCars;
	ArrayList<Car> cars = new ArrayList<Car>();
	NodeVisitor visitor = new NodeVisitor() {
		
		@Override
		public void visitTag(Tag tag) {
			String name = tag.getTagName();
			if ("tr".equalsIgnoreCase(name)
					&& (tag.getAttribute("bgcolor") != null 
							&& (tag.getAttribute("bgcolor").contains("f0f0f0") 
									|| tag.getAttribute("bgcolor").contains("#BBBBBB"))
									&& tag.getAttribute("HEIGHT").equals("26"))) {
				
				cars.add(extractInformation(tag));
				countCars++;
				
			}
		}
	};


	
	public ArrayList<Car> performSearch() throws IOException {

		for (Annotation clazz : this.getClass().getAnnotations()) {
			if (clazz instanceof InternalPages) {
				Url[] urls = (this.getClass().getAnnotation(InternalPages.class).value());
				
				countCars =0 ;
				
				for (Url url : urls) {
					String responseBody = ConnectionUtils.get(url.value());
					Parser parser = new Parser(new Lexer(responseBody));
					try {
						parser.visitAllNodesWith(visitor);
					} catch (ParserException e) {
						e.printStackTrace();
					}
					if (this.countCars == 0 ){
						System.out.println(url.value() + " is not returning cars. Review");
					}
					
				}
			}
		}

		return cars;

	}

	/**
	 * @param line
	 * @return
	 * 
	 * Default line for Autobello's site is
	 * <tr class="txt" style="cursor: pointer;" onclick="javascript: abrirVeiculo('449');">
	 * <td class="txt" height="20">AUDI</td>
	 * <td class="txt">A6 2.8</td>
	 * <td class="txt">1995</td>
	 * <td class="txt">1995</td>
	 * <td class="txt">BZM0202</td>
	 * <td class="txt">VERMELHA</td>
	 * <td class="txt">22.500,00</td>
	 * <td class="txt"><img src="../imagens/sistema/maquina.gif"></td>
	 * </tr>
	 * 
	 */
	public Car extractInformation(Tag line) {
		Car car = new Car();
		int count = 1;
		try {

			NodeList details = line.getChildren();
			details = details.extractAllNodesThatMatch(new NodeFilter() {
				public boolean accept(Node arg0) {
					if (arg0 instanceof TableColumn) {
						return true;

					}

					return false;
				}

			});

			Pattern intOnly = Pattern.compile("\\d*");

			try{
			car.setMontadora(details.elementAt(1).getChildren().elementAt(0).getChildren().elementAt(2).getText());
			}
			catch (Exception e) {
				e.printStackTrace();
			}
			
			car.setModelo(details.elementAt(2).getChildren().elementAt(0).getChildren().elementAt(2).getText());

			// ano fabricacao
			String anoFabricacao = details.elementAt(3).getChildren().elementAt(0).getChildren().elementAt(2).getText();
			Matcher matcher = intOnly.matcher(anoFabricacao);
			if (matcher.find()) {
				car.setAnoFabricacao(new Integer(matcher.group()));
			} else {
				car.setAnoFabricacao(new Integer(anoFabricacao));
			}
			car.setPlaca(details.elementAt(4).getChildren().elementAt(0).getChildren().elementAt(2).getText());
			car.setCor(details.elementAt(5).getChildren().elementAt(0).getChildren().elementAt(2).getText());
			car.setCombustivel(details.elementAt(6).getChildren().elementAt(0).getChildren().elementAt(2).getText());
			car.setValor(details.elementAt(7).getChildren().elementAt(0).getChildren().elementAt(2).getText());
			car.setUrl("http://www.autocarro.com.br/"+ ((LinkTag) details.elementAt(0).getChildren().elementAt(0)).getLink());
			car.setRevenda(new Seller(this.getClass().getSimpleName()));

		} catch (Exception e) {
			e.printStackTrace();
		}

		return car;
		
		
	}


}
